package com.als.healthymananger.service.impl;

import com.als.healthymananger.entity.Archive;
import com.als.healthymananger.mapper.ArchivesMapper;
import com.als.healthymananger.service.ArchivesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aion
 * @since 2021-07-21
 */
@Slf4j
@Service
public class ArchivesServiceImpl extends ServiceImpl<ArchivesMapper, Archive> implements ArchivesService {

    @Override
    public String generateArchiveId() {
        Calendar calendar = Calendar.getInstance();
        String year = String.valueOf(calendar.get(calendar.YEAR));
        String month;
        if (calendar.get(calendar.MONTH) < 10){
            month = "0"+String.valueOf(calendar.get(calendar.MONTH));
        } else {
            month = String.valueOf(calendar.get(calendar.MONTH));
        }


        String day = String.valueOf(calendar.get(calendar.DATE));
        String hour = String.valueOf(calendar.get(calendar.HOUR_OF_DAY));
        String min = String.valueOf(calendar.get(calendar.MINUTE));
        String secound = String.valueOf(calendar.get(calendar.SECOND));
        year = year.substring(2);

        // 查看档案号是否已存在，若已存在重新生成
        String archiveId = "";
        do {
            Random random = new Random();
            String randomNum1 = String.valueOf(random.nextInt(10));
            String randomNum2 = String.valueOf(random.nextInt(10));

            archiveId = year+month+day+hour+min+secound+randomNum1+randomNum2;
        }while (getById(archiveId) != null);

        log.info("生成档案号: {}", archiveId);

        return archiveId;
    }
}
